package cn.kuporo.seckill.common.lock.redisson;

import cn.hutool.core.util.StrUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: kuporo
 * @since: 2025/7/8
 * @description: Redisson配置
 */
@Configuration
@ConditionalOnProperty(name = "distributed.lock.type", havingValue = "redisson")
public class RedissonConfig {
    @Value("${redis.address}")
    private String redisAddress;

    @Value("${spring.data.redis.password}")
    private String redisPassword;

    @Bean(name = "redissonClient")
    @ConditionalOnProperty(name = "redis.arrange.type", havingValue = "single")
    public RedissonClient singleRedissonClient() {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        if (StrUtil.isNotBlank(redisPassword)){
            singleServerConfig.setPassword(redisPassword);
        }
        singleServerConfig.setAddress(redisAddress);
        singleServerConfig.setDatabase(0);
        return Redisson.create(config);
    }

    @Bean(name = "redissonClient")
    @ConditionalOnProperty(name = "redis.arrange.type", havingValue = "cluster")
    public RedissonClient clusterRedissonClient(){
        Config config = new Config();

        // 处理集群节点配置
        List<String> nodeList = Arrays.stream(redisAddress.split(","))
                .map(String::trim)
                .filter(node -> !node.isEmpty())
                .map(node -> node.startsWith("redis://") ? node : "redis://" + node)
                .collect(Collectors.toList());
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        if (StrUtil.isNotBlank(redisPassword)){
            clusterServersConfig.setPassword(redisPassword);
        }
        clusterServersConfig.setNodeAddresses(nodeList);
        return Redisson.create(config);
    }

}
